package biz.datalk.industrialland.common.util;

import biz.datalk.industrialland.common.exception.ServiceException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author tarofang@163.com
 * @date 2024-01-22
 */
@Component
public class GenOrderNoUtil {
    public static final String ORDER_NO_INCR_KEY_PREFIX = "ORDER_NO_INCR:";

    private final RedisUtil redisUtil;

    @Autowired
    public GenOrderNoUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public String genOrderNoWithVendor(Date now, String vendor) {
        String prefix = StringUtils.EMPTY;
        if (StringUtils.isBlank(vendor)) {
            return genOrderNo(now, prefix);
        }

        String trimVendor = vendor.trim();
        if (StringUtils.equals("hk", trimVendor)) {
            prefix = "10";
        }
        if (StringUtils.equals("lk", trimVendor)) {
            prefix = "20";
        }


        return genOrderNo(now, prefix);
    }

    private String genOrderNo(Date now, String prefix) {
        prefix = StringUtils.trimToEmpty(prefix);
        if (prefix.length() > 2) {
            throw new ServiceException("订单号前缀错误");
        }
        // 生成订单号 最大长度32
        // 长度 14
        String fmt = DateFormatUtils.format(now, "yyyyMMddHHmmss");
        // 长度 10
        String incrKey = ORDER_NO_INCR_KEY_PREFIX.concat(DateFormatUtils.format(now, "yyyyMMdd"));
        long incr = redisUtil.incr(incrKey, 1L);
        // String middle = StringUtils.isEmpty(prefix) ? String.format("%010d", incr) : String.format("%08d", incr);
        String middle = StringUtils.isEmpty(prefix) ? String.format("%04d", incr) : String.format("%02d", incr);
        // 长度 6
        // String suffix = RandomStringUtils.random(4, Boolean.FALSE, Boolean.TRUE);
        String suffix = RandomStringUtils.random(2, Boolean.FALSE, Boolean.TRUE);
        return prefix.concat(fmt).concat(middle).concat(suffix);
    }

}
